package org.hbnu.xiaomi.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.hbnu.xiaomi.entity.Users;
import org.hbnu.xiaomi.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

//用户请求控制器
@Controller
public class UsersController {
    //需要用户服务对象
    @Autowired
    UsersService usersService;
    //注册 请求地址是/registration
    //注册成功返回ok，注册失败返回fail或失败理由
    //用户注册需要 账号、密码、重复密码、姓名、性别、年龄、电话、地址
    @RequestMapping("/registration")
    @ResponseBody
    public String registration(@RequestBody Map<String, String>map){
        String email=map.get("email");
        String password=map.get("password");
        String password2=map.get("password2");
        String nickname=map.get("nickname");
        String age=map.get("age");
        String sex=map.get("sex");
        String phone=map.get("phone");
        String address=map.get("address");


   //输出调试
        System.out.println("email=" + email);
        System.out.println("password=" + password);

        //注册条件检查
        if (password.length() < 6) {
            return "密码长度必须大于6";
        }
        if (!password.equals(password2)) {
            return "您输入的2次密码不一致";
        }
        if (password.trim().equals(" ") || password.equals("")) {
            return "您输入的密码不能包括空格或全为空格";
        }

        if (usersService.getUserByEmail(email) != null) {
            return "您输入的邮箱已注册！";
        }

        Users users = new Users();
        users.setEmail(email);
        users.setPassword(password);
        users.setNickname(nickname);
        users.setAge(Integer.parseInt(age));
        users.setSex(Integer.parseInt(sex));
        users.setPhone(phone);
        users.setAddress(address);

        //添加用户
        usersService.addUser(users);
        System.out.println("注册成功");
        return "注册成功";


    }

    //登录（用户查询）
    //用户登录需要接受，邮箱(email)和密码（password）
    //如果登录成功返回 ok，登录失败返回 fail
    @RequestMapping("/login")
    @ResponseBody
public String login(@RequestBody Map<String,String> maps, HttpServletRequest request){

        String email=maps.get("email");
        String password=maps.get("password");

        System.out.println("email:"+email);
        System.out.println("password:"+password);

        if(usersService.getUserByEmail(email)==null){
            return "用户不存在";
        }

        if(!usersService.getUserByEmail(email).getPassword().equals(password)){
            return "密码错误";
        }
        //请求对象使用会话技术去记住用户(时间：30分钟)
        request.getSession().setAttribute("user_id",Users.getId());




        return "ok";
}
    // 用户注销
// 用户点击注销按钮后，清除会话信息，实现用户登出
    @RequestMapping("/logout")
    @ResponseBody
    public String logout(HttpServletRequest request) {
        // 清除会话信息
        request.getSession().invalidate();
        System.out.println("当前用户已退出");
        // 返回登出成功信息
        return "logout success";
    }

    @RestController
    @SessionAttributes("user_id")
    public class LoginStatusController {

        // 假设你有一个UserService来处理用户相关的数据库操作
        @Autowired
        private UsersService userService;

        @GetMapping("/check-login-status")
        public ResponseEntity<?> checkLoginStatus(HttpSession session) {
            // 从session中获取用户ID
            Integer user_id = (Integer) session.getAttribute("user_id");

            // 如果用户ID存在，则用户已登录
            if (user_id != null) {
                String nickname = userService.findNicknameById(user_id);
                // 构建并返回响应
                Map<String, Object> response = new HashMap<>();
                response.put("user_id", user_id);
                response.put("nickname", nickname);
                return ResponseEntity.ok(response);
            } else {
                // 用户未登录，返回401状态码
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
            }
        }
    }

    //
}
